package com.kfpanda.spring.batch.incrementer.mongo;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersIncrementer;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;


@Repository
public class MongodbIncrementer implements JobParametersIncrementer {
	@Resource(name="mongoIncrementerTemplate")
	private MongoTemplate mongoTemplate;
	
	public MongoIncrementBean findIncrementer(JobParameters parameters){
		Criteria criteria = new Criteria();
		Map<String, JobParameter> jobParams = parameters.getParameters();
    	for( Iterator<Entry<String, JobParameter>> itr = jobParams.entrySet().iterator(); 
    			itr.hasNext(); ){
    		Entry<String, JobParameter> entry = itr.next();
    		if(entry.getKey().startsWith(IncrementerMongodb.INCREMENTER_PREX)){
	    		JobParameter param = entry.getValue();
	    		//去掉前缀
	    		String key = entry.getKey().replace(IncrementerMongodb.INCREMENTER_PREX, "");
	    		criteria.and(key).is(param.getValue());
    		}
    	}
    	Query query = new Query(criteria);
    	MongoIncrementBean incremBean = mongoTemplate.findOne(query, 
    			MongoIncrementBean.class, IncrementerMongodb.INCREMENTER_COLLECT_NAME);
    	return incremBean;
	}
	
    public JobParameters getNext(JobParameters parameters) {
    	MongoIncrementBean incremBean = findIncrementer(parameters);
    	String beforeIncrem = StringUtils.isBlank(incremBean.getBeforeIncrementer()) ?
    				incremBean.getIncrementer() : incremBean.getBeforeIncrementer();
    	JobParametersBuilder paramBuilder = new JobParametersBuilder(parameters);
    	JobParametersBuilder newParamBuilder = new JobParametersBuilder(parameters);
    	paramBuilder.addString(IncrementerMongodb.INCREMENTER_NAME, beforeIncrem);
    	parameters = paramBuilder.toJobParameters();
    	newParamBuilder.addString(
    			IncrementerMongodb.INCREMENTER_NAME, incremBean.getIncrementer());
    	
        return newParamBuilder.toJobParameters();
    }
}
